package bean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import dao.ServicoDAO;
import model.Servico;

@ManagedBean
@ViewScoped
public class ServicoBean {

	private Servico servico;
	private DataModel listaServicos;
	private List<Servico> list;
	private String currentAction;

	public ServicoBean() {
		servico = new Servico();
	}

	public Servico getServico() {
		return servico;
	}

	public void setServico(Servico servico) {
		this.servico = servico;
	}

	public void alterarOuInserirServico(ActionEvent actionEvent) {

		ServicoDAO servicoDAO = new ServicoDAO();
		
		if (this.currentAction.equalsIgnoreCase("Inserir")) {
			servicoDAO.insert(servico);
			clearCurrentAction();
		}

		if (this.currentAction.equalsIgnoreCase("Alterar")) {
			
			servicoDAO.update(servico);
			clearCurrentAction();
		}		
	}

	public void excluirServico(ActionEvent actionEvent) {

		ServicoDAO servicoDAO = new ServicoDAO();
		servicoDAO.delete(servico);
	}

	public DataModel getListarServicos() {

		ServicoDAO servicoDAO = new ServicoDAO();

		if (this.list == null) {
			list = servicoDAO.selectAll();
			listaServicos = new ListDataModel(list);
		}
		return listaServicos;
	}

	public void prepararAdicionarServico(ActionEvent actionEvent) {
		this.currentAction = "Inserir";
		this.servico = new Servico();
	}

	public void prepararAlterarServico(ActionEvent actionEvent) {
		this.currentAction = "Alterar";
		servico = (Servico) (listaServicos.getRowData());
	}

	public void prepararExcluirServico(ActionEvent actionEvent) {
		servico = (Servico) (listaServicos.getRowData());
	}
	
	public void clearCurrentAction(){
		this.currentAction = "";
	}
}
